package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.ClientUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.resource.OperatorUserSystemHolder;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ClientProductSys;
import com.ruoyi.system.domain.ClientUserProductRelationSys;
import com.ruoyi.system.mapper.ClientUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author xiaom
 * @Date 2021/1/26 14:10
 * @Version 1.0.0
 * @Description <Web魔词网页版 登录校验>
 **/
@Service("merchantwordsUserDetailsService")
public class WebMerchantwordsUserDetailService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(WebMerchantwordsUserDetailService.class);

    @Autowired
    private ClientUserMapper clientUserMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ClientUser user = clientUserMapper.findByUsername(username);
        if(StringUtils.isNull(user)){
            log.info("[WEB]登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }else if (UserStatus.DELETED.getCode().equals(user.getStatus())) {
            log.info("[WEB]登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("[WEB]登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        //检测是否包含web权限
        Date expireTime = containWebAuthority(user.getUserId());
        //设置过期时间
        user.setExpireTime(expireTime);

        LoginUser loginUser = new LoginUser(user);
        loginUser.setOperatorUserSystem(OperatorUserSystemHolder.get());


        return loginUser;
    }

    /**
     * 共用以前的clientUser逻辑 所以判断是否包含web权限
     */
    private Date containWebAuthority(Long userId){
        //获取魔词web 产品id
        ClientProductSys clientProduct = clientUserMapper.findClientProductByName("merchantwords_web");
        if(StringUtils.isNull(clientProduct)){
            log.error("[WEB]登录 => 不存在魔词客户端信息,请初始化");
            throw new BaseException("服务器内部错误");
        }
        ClientUserProductRelationSys clientUserProductRelation = clientUserMapper.findWebAuthorityByUserId(userId,clientProduct.getId());
        if(StringUtils.isNull(clientUserProductRelation)){
            String message = String.format("[WEB]权限认证失败.userId:[%s]",userId);
            log.error(message);
            throw new BaseException(message);
        }
        //验证是否过期
        if(clientUserProductRelation.getExpireTime() != null && clientUserProductRelation.getExpireTime().before(new Date())){
            String message = String.format("[WEB]账号已到期,请续费.userId:[%s]",userId);
            log.error(message);
            throw new BaseException("账号已到期,请续费");
        }

        return clientUserProductRelation.getExpireTime();
    }


}
